package sample;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sample.com.nky.bean.User;

/**
 * UI控件和域模型之间的绑定
 */

public class Main extends Application {

    private final static String MY_PASS = "passwd";// 初始密码
    private final static BooleanProperty accessGranted = new SimpleBooleanProperty(false);


    @Override
    public void start(Stage primaryStage) throws Exception {

        Group group = new Group();
        Scene scene = new Scene(group, 320, 100);

        User user = new User();

        Text text = new Text();
        //将user的userName属性值绑定到Text上
        text.textProperty().bind(user.userNameProperty());

        PasswordField passwordField = new PasswordField();
        //将passwordField的输入值绑定到User的password上
        passwordField.setText("passwd");
        user.passwordProperty().bind(passwordField.textProperty());


        //给passwordFiled添加监听事件，只有当改变文本框内容改变以后有访问权限，否则即使初始的密码已经显示在文本框中，也会显示no access
        passwordField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

                boolean granted = passwordField.getText().equals(MY_PASS);

                accessGranted.set(granted);

                if (granted) {
                    primaryStage.setTitle("");
                }
            }
        });

        //设置enter 键点击事件
        passwordField.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (accessGranted.get()) {
                    System.out.println("granted access : " + user.getUserName());
                    System.out.println("password : " + user.getPassword());
                } else {
                    System.out.println("no access");
                }
            }
        });

        VBox vBox = new VBox();

        vBox.getChildren().addAll(text, passwordField);
        vBox.setLayoutX(12);
        vBox.setLayoutY(12);

        group.getChildren().addAll(vBox);
        primaryStage.setScene(scene);

        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}
